
import ResizeObserver from 'resize-observer-polyfill';
import store from '@/store';

const isServer = typeof window === 'undefined';

/* istanbul ignore next */
const resizeHandler = function (entries) {
    for (let entry of entries) {
        const listeners = entry.target.__resizeListeners__ || [];
        if (listeners.length) {
            listeners.forEach(fn => {
                fn();
            });
        }
    }
};

/* istanbul ignore next */
export const addResizeListener = function (element, fn) {
    if (isServer) { return; }
    if (!element.__resizeListeners__) {
        element.__resizeListeners__ = [];
        element.__ro__ = new ResizeObserver(resizeHandler);
        element.__ro__.observe(element);
    }
    element.__resizeListeners__.push(fn);
};

/* istanbul ignore next */
export const removeResizeListener = function (element, fn) {
    if (!element || !element.__resizeListeners__) { return; }
    element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1);
    if (!element.__resizeListeners__.length) {
        element.__ro__.disconnect();
    }
};

/**
 * How to use
 * <el-table height="100px" v-el-height-adaptive-table="{bottomOffset: 30}">...</el-table>
 * el-table height is must be set
 *  bottomOffset: 30(default)   // The height of the table from the bottom of the page.
 */

const doResize = (el, binding, vnode) => {
    const { componentInstance: $table } = vnode;

    const { value } = binding;
    if (!value.fixedHeader) {
        return;
    }

    if (!$table.height) {
        throw new Error('el-$table must set the height. Such as height=\'100px\'');
    }
    const bottomOffset = (value && value.bottomOffset) || 84;

    if (!$table) { return; }
    const height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset;
    if ($table.layout) {
        setTimeout(() => {
            $table.layout.setHeight(height + 'px');
            $table.doLayout();
        }, 200);
    } else {
        setTimeout(() => {
            document.querySelector('#' + binding.value.id).style.height = height + 'px';
        });
    }
};

export default {
    bind (el, binding, vnode) {
        el.resizeListener = () => {
            doResize(el, binding, vnode);
        };

        addResizeListener(window.document.body, el.resizeListener);
    },
    inserted (el, binding, vnode) {
        doResize(el, binding, vnode);
    },
    unbind (el) {
        removeResizeListener(window.document.body, el.resizeListener);
    }
};
